package com.treasure.mall.zbqmallapi.controller;

import com.treasure.mall.biz.dto.user.UserAddressSaveDTO;
import com.treasure.mall.biz.entity.embeddable.ReceivingInfo;
import com.treasure.mall.biz.entity.user.UserAddressPO;
import com.treasure.mall.biz.entity.user.UserPO;
import com.treasure.mall.biz.service.core.user.UserAddressService;
import com.treasure.mall.zbq.common.annotation.CurrentUser;
import com.treasure.mall.zbq.common.base.ApiResult;
import com.treasure.mall.zbqmallapi.annotation.AccessControl;
import com.treasure.mall.zbqmallapi.vo.user.UserAddressVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户收获地址相关接口
 *
 * @author allan
 * @version 1.0.0
 * @date 2020/7/6
 */
@RestController
@RequestMapping("/user/address")
@Api(tags = "用户模块")
@AccessControl(needLogin = true)
public class UserAddressController {
    @Autowired
    private UserAddressService userAddressService;

    @PostMapping("/edit")
    @ApiOperation("添加或更新用户收获地址")
    public ApiResult edit(@CurrentUser UserPO userPO, UserAddressSaveDTO saveDTO, ReceivingInfo receivingInfo) {
        saveDTO.setUserId(userPO.getUserId());
        saveDTO.setReceivingInfo(receivingInfo);
        userAddressService.save(saveDTO);

        return ApiResult.ok();
    }

    @PostMapping("/setDefault/{addressId}")
    @ApiOperation("设置某个收获地址为默认地址")
    public ApiResult setDefault(@CurrentUser UserPO userPO, @PathVariable("addressId") Long addressId) {
        userAddressService.setDefault(addressId, userPO.getUserId());

        return ApiResult.ok();
    }

    @PostMapping("/delete/{addressId}")
    @ApiOperation("删除某个售后地址")
    public ApiResult delete(@PathVariable("addressId") Long addressId) {
        userAddressService.delete(addressId);

        return ApiResult.ok();
    }

    @PostMapping("/findDefault")
    @ApiOperation("得到某个用户的默认收获地址")
    public ApiResult findDefault(@CurrentUser UserPO userPO) {
        UserAddressPO userAddressPO = userAddressService.findDefault(userPO.getUserId());

        return ApiResult.ok(new UserAddressVO(userAddressPO));
    }

    @PostMapping("/findByUser")
    @ApiOperation("得到某个用户的收获地址列表")
    public ApiResult findByUser(@CurrentUser UserPO userPO) {
        List<UserAddressPO> userAddressPOS = userAddressService.findByUser(userPO.getUserId());

        List<UserAddressVO> userAddressVOS = new ArrayList<>();
        userAddressPOS.forEach(p -> userAddressVOS.add(new UserAddressVO(p)));

        return ApiResult.ok(userAddressVOS);
    }
}
